package com.xnx.bincker.leader.service.impl;

import com.xnx.bincker.leader.core.repository.BasicRepository;
import com.xnx.bincker.leader.core.domain.BasicEntity;
import com.xnx.bincker.leader.service.BasicService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.util.List;
import java.util.Optional;

/**
 * 基础服务类实现
 * @param <T> 实体类型
 */
@Transactional
public class BasicServiceImpl<T extends BasicEntity, S extends Serializable> implements BasicService<T, S> {
	BasicRepository<T, S> repository;

	@Autowired
    public void setBasicRepository(BasicRepository<T, S> repository) {
        this.repository = repository;
    }

    public Optional<T> findById(S id){
		return repository.findById(id);
	}

	public Optional<T> findOne(Example<T> example){
		return repository.findOne(example);
	}

	public T getOne(S id){
		return repository.getOne(id);
	}

	public List<T> findAll(){
		return repository.findAll();
	}

	public List<T> findAll(Sort sort){
		return repository.findAll(sort);
	}

	public Page<T> findAll(Pageable pageable){
		return repository.findAll(pageable);
	}

	public List<T> findAll(Example<T> example){
		return repository.findAll(example);
	}

	public List<T> findAll(Example<T> example, Sort sort){
		return repository.findAll(example, sort);
	}

	public Page<T> findAll(Example<T> example, Pageable pageable){
		return repository.findAll(example, pageable);
	}

	public List<T> findAllById(Iterable<S> ids){
		return repository.findAllById(ids);
	}

	public long count(){
		return repository.count();
	}

	public long count(Example<T> example){
		return repository.count(example);
	}

	public void delete(T t){
		repository.delete(t);
	}

	public void deleteById(S id){
		repository.deleteById(id);
	}

	public void deleteAll(){
		repository.deleteAllInBatch();
	}

	public void deleteInBatch(Iterable<T> objs){
		repository.deleteInBatch(objs);
	}

	public T save(T t){
		return repository.save(t);
	}

	public T saveAndFlush(T t){
	    return repository.saveAndFlush(t);
    }

    public boolean exists(Example<T> t){
	    return repository.exists(t);
    }

    public boolean exists(S id){
	    return repository.count((Specification<T>) (root, criteriaQuery, criteriaBuilder) -> criteriaBuilder.equal(root.get("id"), id)) > 0;
    }

	public List<T> saveAll(Iterable<T> entities){
		return repository.saveAll(entities);
	}

	public void flush(){
	    repository.flush();
    }
}
